﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using LSEntity;
using LSInterFace;
using LSUtility;

namespace LSBLL
{
    public class ControllerCommon<T, TControllerCheck, TResult> : Controller
        where T : IControllerFormat<TResult>, new()
        where TControllerCheck : IControllerCheck, new()
    {
        protected WebPageConfig WebPageConfig { get; set; }

        protected MemberEntity Member
        {
            get { return MemberBLL.MemberCurrent; }
        }

        protected TResult CommonModel
        {
            get { return new T().GetModel(WebPageConfig, Member); }
        }

        #region Check

        protected int Check<T1, T2, T3, T4>(T1 t1, T2 t2, T3 t3, T4 t4)
        {
            return new TControllerCheck().ControllerCheck(t1, t2, t3, t4);
        }

        protected int Check<T1, T2, T3>(T1 t1, T2 t2, T3 t3)
        {
            return new TControllerCheck().ControllerCheck(t1, t2, t3);
        }

        protected int Check<T1, T2>(T1 t1, T2 t2)
        {
            return new TControllerCheck().ControllerCheck(t1, t2);
        }

        protected int Check<T1>(T1 t1)
        {
            return new TControllerCheck().ControllerCheck(t1);
        }

        #endregion

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var t = new T();
            var r = new Regex(@"(?<=http://).*?(?=\.)");
            var url = filterContext.HttpContext.Request.Url;
            if (url != null)
            {
                var m = r.Match(url.AbsoluteUri);
                if (m.Success || !String.IsNullOrEmpty(m.Value))
                {
                    WebPageConfig = new WebPageConfig
                                        {
                                            Area = t.Area,
                                            LocalName = m.Value,
                                        };

                }
            }
            base.OnActionExecuting(filterContext);
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var model = filterContext.Controller.ViewData.Model as WebPageConfig;
            if (model != null)
            {
                var t = new T();
                model.LocalName = WebPageConfig.LocalName;
                model.Area = WebPageConfig.Area;
                filterContext.Controller.ViewData.Model = model;
                t.Init(model, Member);
            }
            base.OnActionExecuted(filterContext);
        }
    }
}
